package com.aivin.mobileApi;

import com.aivin.entity.*;
import com.aivin.pointsApi.*;
import com.aivin.service.PicService;
import com.aivin.service.PointsService;
import com.aivin.service.UserService;
import com.aivin.utils.MyStringUtils;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *  restful设计
 */
@Controller//@Service @Component
@RequestMapping("/pointsApi")
public class PointsController {




    @Autowired
    private PointsService pointsService ;



    /***
     *  http://192.168.0.119:8081/findYou/pointsApi/getCreditConsumeResult
     *  根据关键字搜索。
     */
    @RequestMapping(value = "/getCreditConsumeResult",
            method = {RequestMethod.POST, RequestMethod.GET},
            produces = "text/html;charset=UTF-8")
    @ResponseBody
    public  void  getCreditConsumeResult(HttpServletRequest  request, HttpServletResponse  response) {

        // test code start -----------------------
        try {

           System.out.print("###########"+request.getRequestURI() );
            System.out.print("###########"+request.getRemoteHost() );


            //其他参数参见 params的属性字段
            //TODO 开发者系统对uid用户扣除credits个积分

            String bizId=  System.currentTimeMillis()+"";//返回开发者系统中的业务订单id  .暂时都返回 1.  data for test   String bizId=todo();
            CreditConsumeResult result=new CreditConsumeResult(true);
            result.setBizId(bizId);
            result.setCredits(  (long) MyStringUtils.getRadomInt(0,500)  );// 用户积分余额



            // response with jsonStr
            response.getWriter().write(result.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    /**
     * http://192.168.0.119:8081/findYou/pointsApi/parseCreditNotify
     * ***/
    @RequestMapping(value = "/parseCreditNotify",
            method = {RequestMethod.POST, RequestMethod.GET},
            produces = "text/html;charset=UTF-8")
    @ResponseBody
    public void parseCreditNotify(HttpServletRequest request, HttpServletResponse response) {
       /**
        *  兑换订单的结果通知请求的解析方法
        *  当兑换订单成功时，兑吧会发送请求通知开发者，兑换订单的结果为成功或者失败，如果为失败，开发者需要将积分返还给用户
        */

        CreditTool tool = new CreditTool(MyConfig.AppKey_duiba, MyConfig.App_Secret_duiba);

        try {
            CreditNotifyParams  params = tool.parseCreditNotify(request);//利用tool来解析这个请求
            String orderNum = params.getOrderNum();
            if (params.isSuccess()) {
                //兑换成功
                System.out.println("###############收到兑吧的通知：积分兑换成功");
            } else {
                //兑换失败，根据orderNum，对用户的金币进行返还，回滚操作
                System.out.println("###############收到兑吧的通知：积分兑换失败，需要进行数据回滚");
            }

            //无论接受到的结果如何，只要开发者收到该请求，请返回 ok 字符串（不含双引号），
            // 否则兑吧将进行重复通知，直到开发者收到或者24小时内最多重复 8 次。
            response.getWriter().write("ok");
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }



    }



/**
 *   http://192.168.0.119:8081/findYou/pointsApi/getLoginUrlByUserId/1
 *
 * ***/

    @RequestMapping(value = "/getLoginUrlByUserId/{userId}",
            method = {RequestMethod.POST, RequestMethod.GET},
            produces = "text/html;charset=UTF-8")
    @ResponseBody
    public   void  getLoginUrlByUserId(@PathVariable  int userId ,HttpServletRequest  request, HttpServletResponse  response) {
        CreditTool tool = new CreditTool(MyConfig.AppKey_duiba, MyConfig.App_Secret_duiba);
        Map params = new HashMap();
        params.put("uid", userId+"");   // not_login
        params.put("credits", getCreditsByUserId(userId)+"");  //用户积分余额  游客的积分为0

//        if (redirect != null) {
//            //redirect是目标页面地址，默认积分商城首页是：http://www.duiba.com.cn/chome/index
//            //此处请设置成一个外部传进来的参数，方便运营灵活配置
//            params.put("redirect", redirect);
//        }


        //此url即为免登录url
        String url = tool.buildUrlWithSign("http://www.duiba.com.cn/autoLogin/autologin?", params);
        System.out.println("##########url=\r\n"+url);
//        url="http://www.duiba.com.cn/autoLogin/autologin?sign=0548e84ee5b8f33b19465120d0529c03&timestamp=1473306419691&uid=1&credits=800&appKey=nhA87TEVxD4jw5yeFjo7cDhgLfa&";
        System.out.println("\r\n"+url);
        try{
            response.getWriter().write(url);
        }catch (Exception e){

        }

//        return url;
    }

    public int  getCreditsByUserId(int userId){
        int credits  = 450 ; // for test
        credits = (userId ==1) ? 800 : 450;
        return  credits ;

    }

/*********************************************************************************************************************/
    /**
     *  get pointTask list
     *
     */


    /****
     *
     http://192.168.0.119:8081/findYou/pointsApi/queryAllPointsTaskFy/0/10
     */
    @RequestMapping(value = "/queryAllPointsTaskFy/{offset}/{limit}",
            method = {RequestMethod.POST, RequestMethod.GET},
            produces = "text/html;charset=UTF-8")
    @ResponseBody
    public  String  queryAllPointsTaskFy(   @PathVariable int offset ,@PathVariable int limit) {
        List<PointsTask>  beanList = pointsService.queryAllPointsTaskFy( offset  , limit) ;
        String jsonStr ="noData";
        if(!(beanList==null || beanList.size()==0)){
            jsonStr = JSON.toJSONString(beanList );
        }

        return jsonStr;
    }


    /****
     *
     http://192.168.0.102:8081/findYou/pointsApi/queryPointsTaskByUserIdFy/3/0/10
     根据用户id 获取悬赏内容 。
     我的悬赏
     传入参数：
     userId: 用户Id
     offset : 偏移量
     limit : 一次获取多少条数据

     返回值： noData ,查询数据为空
     其他json ：正常的数据
     */
    @RequestMapping(value = "/queryPointsTaskByUserIdFy/{userId}/{offset}/{limit}",
            method = {RequestMethod.POST, RequestMethod.GET},
            produces = "text/html;charset=UTF-8")
    @ResponseBody
    public  String  queryPointsTaskByUserIdFy(  @PathVariable int userId, @PathVariable int offset ,@PathVariable int limit) {
        List<PointsTask>  beanList = pointsService.queryPointsTaskByUserIdFy( userId,offset  , limit) ;
        String jsonStr ="noData";
        if(!(beanList==null || beanList.size()==0)){
            jsonStr = JSON.toJSONString(beanList );
        }

        return jsonStr;
    }



    /****
     *
     http://192.168.0.119:8081/findYou/pointsApi/publishTask
     */
    @RequestMapping(value = "/publishTask",
            method = {RequestMethod.POST},
            produces = "text/html;charset=UTF-8"
    )
    @ResponseBody
    public String  publishTask ( @RequestParam("jsonStr") String jsonStr ,@RequestParam("key2") String key2    ){

        System.out.println("jsonStr#############\n"+jsonStr);

        PointsTask  bean = JSON.parseObject(jsonStr, PointsTask.class);
        int state= pointsService.publishTask(bean) ;
        return  state+"";

    }


    /****
     *
     http://192.168.0.119:8081/findYou/pointsApi/publishReply
     */
    @RequestMapping(value = "/publishReply",
            method = {RequestMethod.POST},
            produces = "text/html;charset=UTF-8"
    )
    @ResponseBody
    public String  publishReply ( @RequestParam("jsonStr") String jsonStr ,@RequestParam("key2") String key2    ){
        System.out.println("jsonStr#############\n"+jsonStr);

        TaskReply bean1   = JSON.parseObject(jsonStr, TaskReply.class);

//        bean1.setReplyId(2);
//        bean1.setTaskId(1);
//        bean1.setUserId(3);
//        bean1.setReplyInfo("你好，我要投稿");
//        bean1.setReplyPicUrl("www.baidu.com");
//        bean1.setRegTime("2016-09-13");

        jsonStr=JSON.toJSONString(bean1);
        System.out.println("jsonStr=>>>\n"+jsonStr);

        TaskReply  bean = JSON.parseObject(jsonStr, TaskReply.class);
        int state= pointsService.publishReply(bean) ;
        return  state+"";

    }




    /****
     *
     http://192.168.0.119:8081/findYou/pointsApi/queryReplyByTaskIdFy/1/0/10
     根据悬赏id查找所有回复稿件
     */
    @RequestMapping(value = "/queryReplyByTaskIdFy/{taskId}/{offset}/{limit}",
            method = {RequestMethod.POST, RequestMethod.GET},
            produces = "text/html;charset=UTF-8")
    @ResponseBody
    public  String  queryReplyByTaskIdFy( @PathVariable int taskId ,   @PathVariable int offset ,@PathVariable int limit) {
        System.out.println("###########"+taskId + "   "+offset +"  "+ limit);
        List<TaskReply>  beanList = pointsService.queryReplyByTaskIdFy(taskId, offset  , limit) ;
        String jsonStr ="noData";
        if(!(beanList==null || beanList.size()==0)){
            jsonStr = JSON.toJSONString(beanList );
        }

        return jsonStr;
    }


    /****
     *
     http://192.168.0.119:8081/findYou/pointsApi/queryReplyByUserIdFy/3/0/10
     根据悬赏id查找所有回复稿件
     */
    @RequestMapping(value = "/queryReplyByUserIdFy/{userId}/{offset}/{limit}",
            method = {RequestMethod.POST, RequestMethod.GET},
            produces = "text/html;charset=UTF-8")
    @ResponseBody
    public  String  queryReplyByUserIdFy( @PathVariable int userId ,   @PathVariable int offset ,@PathVariable int limit) {

        List<TaskReply>  beanList = pointsService.queryReplyByUserIdFy(userId, offset  , limit) ;
        String jsonStr ="noData";
        if(!(beanList==null || beanList.size()==0)){
            jsonStr = JSON.toJSONString(beanList );
        }

        return jsonStr;
    }



}
